import { randomString, getTimestamp } from './';
import { baseUrl } from '../api';
import Tips from './tips';
import CryptoJS from 'crypto-js';
import { getHeaderAES } from './AESCrypt';

/**
 * 从服务器获取AccessToken的方法
 */
export async function auth() {
  console.log('auth 被执行');
  const res = await wxLogin().then(authRequest);
  console.log(res);
  const accessToken = res.token.access_token;
  wx.setStorageSync('accessToken', accessToken);
  wx.setStorageSync('expiredTime', res.token.expired_at);
  return accessToken;
}

/**
 * 小程序原生api 获取登录的code属性值
 */
function wxLogin() {
  Tips.loading();
  return new Promise((resolve) => {
    wx.login({
      success: function(res) {
        console.log('code 获取： ', res);
        const params = generateSignature(res.code);
        console.log('请求参数', params);
        return resolve(params);
      }
    });
  });
}

/**
 * 接口登录方法 获取accessToken
 * @param {*} params
 */
function authRequest(params) {
  return new Promise((resolve) => {
    wx.request({
      url: `${baseUrl}/oauth2/wechat`,
      method: 'POST',
      data: params,
      success: function(res) {
        console.log(res);
        Tips.loaded();
        if (res.data.code === 200) {
          return resolve(res.data.data);
        } else {
          Tips.error(res.data.msg);
        }
      },
      fail: function(e) {
        console.log(e);
      }
    });
  });
}

/**
 * 生成签名字符串
 * @param {*} code
 */
function generateSignature(code) {
  const nonce = randomString(32);
  const appid = '2018092659';
  const systemInfo = wx.getSystemInfoSync();
  let platform = 'android';
  if (iOSDevice(systemInfo.system)) {
    platform = 'ios';
  }
  const model = systemInfo.model;

  let params = {
    appid: appid,
    code: code,
    timestamp: getTimestamp(),
    platform: platform,
    model: model,
    build: 1
  };
  let str = '';
  for (let key of Object.keys(params).sort()) {
    str += params[key];
  }
  let secret = 'y5fEw4Lor7CDHr4Ee7M8MbmVXuUG4Jns';
  let sign = CryptoJS.SHA256(secret + str + nonce).toString(CryptoJS.enc.Hex);

  params['nonce'] = nonce;
  params['sign'] = sign;
  return params;
}

/**
 * 判断是否是iOS的设备
 * @param {*} string
 */
function iOSDevice(string) {
  return /^iOS/.test(string);
}

/**
 * 对请求头的token进行AES加密
 * @param {*} data
 */
export function cryptoToken(data) {
  return getHeaderAES(data);
}

/**
 * 判断token过期时间，判断是否要重新请求
 */
export function needRequestToken() {
  const expiredTime = wx.getStorageSync('expiredTime');
  if (!expiredTime) {
    return;
  }
  const now = new Date().getTime();
  if ((now + 86400 * 5) < expiredTime * 1000) {
    return;
  }
  wx.removeStorageSync('accessToken');
  wx.removeStorageSync('expiredTime');
}
